#!/bin/bash

# 监控系统启动脚本
# 用于启动fy-space项目的监控功能

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="fy-space"
JAR_NAME="fy-space.jar"
LOG_DIR="logs"
PID_FILE="fy-space.pid"

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查Java环境
check_java() {
    if ! command -v java &> /dev/null; then
        print_message $RED "错误: 未找到Java环境，请先安装Java 8或更高版本"
        exit 1
    fi
    
    JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2)
    print_message $GREEN "检测到Java版本: $JAVA_VERSION"
}

# 检查项目文件
check_project() {
    if [ ! -f "$JAR_NAME" ]; then
        print_message $RED "错误: 未找到项目JAR文件: $JAR_NAME"
        print_message $YELLOW "请确保在项目根目录下运行此脚本"
        exit 1
    fi
    
    # 创建日志目录
    if [ ! -d "$LOG_DIR" ]; then
        mkdir -p "$LOG_DIR"
        print_message $GREEN "创建日志目录: $LOG_DIR"
    fi
}

# 检查进程是否已运行
check_running() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null 2>&1; then
            print_message $YELLOW "项目已在运行中，PID: $PID"
            return 0
        else
            print_message $YELLOW "发现无效的PID文件，正在清理..."
            rm -f "$PID_FILE"
        fi
    fi
    return 1
}

# 启动项目
start_project() {
    print_message $BLUE "正在启动 $PROJECT_NAME..."
    
    # 设置JVM参数
    JVM_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC -XX:+HeapDumpOnOutOfMemoryError"
    JVM_OPTS="$JVM_OPTS -XX:HeapDumpPath=$LOG_DIR/"
    JVM_OPTS="$JVM_OPTS -Dspring.profiles.active=prod"
    JVM_OPTS="$JVM_OPTS -Dfile.encoding=UTF-8"
    
    # 启动应用
    nohup java $JVM_OPTS -jar $JAR_NAME > "$LOG_DIR/startup.log" 2>&1 &
    
    # 保存PID
    echo $! > "$PID_FILE"
    
    # 等待启动
    print_message $BLUE "等待应用启动..."
    sleep 5
    
    # 检查启动状态
    if ps -p $(cat "$PID_FILE") > /dev/null 2>&1; then
        print_message $GREEN "✅ $PROJECT_NAME 启动成功！"
        print_message $GREEN "PID: $(cat $PID_FILE)"
        print_message $GREEN "日志文件: $LOG_DIR/startup.log"
        print_message $GREEN "监控接口: http://localhost:8633/api/admin/dashboard"
    else
        print_message $RED "❌ $PROJECT_NAME 启动失败！"
        print_message $YELLOW "请查看日志文件: $LOG_DIR/startup.log"
        rm -f "$PID_FILE"
        exit 1
    fi
}

# 停止项目
stop_project() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null 2>&1; then
            print_message $BLUE "正在停止 $PROJECT_NAME (PID: $PID)..."
            kill $PID
            
            # 等待进程结束
            for i in {1..30}; do
                if ! ps -p $PID > /dev/null 2>&1; then
                    print_message $GREEN "✅ $PROJECT_NAME 已停止"
                    rm -f "$PID_FILE"
                    return 0
                fi
                sleep 1
            done
            
            # 强制杀死进程
            print_message $YELLOW "强制停止进程..."
            kill -9 $PID
            print_message $GREEN "✅ $PROJECT_NAME 已强制停止"
            rm -f "$PID_FILE"
        else
            print_message $YELLOW "进程未运行"
            rm -f "$PID_FILE"
        fi
    else
        print_message $YELLOW "未找到PID文件"
    fi
}

# 重启项目
restart_project() {
    print_message $BLUE "重启 $PROJECT_NAME..."
    stop_project
    sleep 2
    start_project
}

# 查看状态
status_project() {
    if check_running; then
        PID=$(cat "$PID_FILE")
        print_message $GREEN "✅ $PROJECT_NAME 正在运行"
        print_message $GREEN "PID: $PID"
        print_message $GREEN "监控接口: http://localhost:8633/api/admin/dashboard"
        
        # 显示系统资源使用情况
        if command -v ps &> /dev/null; then
            print_message $BLUE "系统资源使用情况:"
            ps -p $PID -o pid,ppid,%cpu,%mem,cmd --no-headers
        fi
    else
        print_message $RED "❌ $PROJECT_NAME 未运行"
    fi
}

# 查看日志
view_logs() {
    if [ -f "$LOG_DIR/startup.log" ]; then
        print_message $BLUE "显示启动日志 (最后50行):"
        tail -n 50 "$LOG_DIR/startup.log"
    else
        print_message $YELLOW "未找到日志文件"
    fi
}

# 监控系统状态
monitor_status() {
    if check_running; then
        PID=$(cat "$PID_FILE")
        print_message $BLUE "监控系统状态..."
        
        # 检查端口是否监听
        if netstat -tuln 2>/dev/null | grep -q ":8633 "; then
            print_message $GREEN "✅ 端口8633正在监听"
        else
            print_message $RED "❌ 端口8633未监听"
        fi
        
        # 测试监控接口
        if command -v curl &> /dev/null; then
            print_message $BLUE "测试监控接口..."
            HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8633/api/admin/health)
            if [ "$HTTP_CODE" = "200" ]; then
                print_message $GREEN "✅ 监控接口响应正常"
            else
                print_message $RED "❌ 监控接口响应异常 (HTTP $HTTP_CODE)"
            fi
        fi
    else
        print_message $RED "❌ 应用未运行，无法监控"
    fi
}

# 显示帮助信息
show_help() {
    echo "fy-space 监控系统管理脚本"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start     启动应用"
    echo "  stop      停止应用"
    echo "  restart   重启应用"
    echo "  status    查看应用状态"
    echo "  logs      查看启动日志"
    echo "  monitor   监控系统状态"
    echo "  help      显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 start      # 启动应用"
    echo "  $0 status     # 查看状态"
    echo "  $0 monitor    # 监控系统"
}

# 主函数
main() {
    case "$1" in
        start)
            check_java
            check_project
            if check_running; then
                print_message $YELLOW "应用已在运行中"
                exit 0
            fi
            start_project
            ;;
        stop)
            stop_project
            ;;
        restart)
            check_java
            check_project
            restart_project
            ;;
        status)
            status_project
            ;;
        logs)
            view_logs
            ;;
        monitor)
            monitor_status
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_message $RED "未知命令: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 